import axios from 'axios'

// 基于axios封装get和post请求
export  default function ajax(url='',params={},type='GET') {
  let promise;
  return new Promise((resolve,reject)=>{
    // 判断请求的方式
    if('GET'===type){
      // 拼接请求的字符串
      let paramsStr = '';
      Object.keys(params).forEach(key=>{paramsStr+=key+'='+params[key]+'&'});
      if(paramsStr!==''){
        paramsStr=paramsStr.substr(0,paramsStr.lastIndexOf('&'));
      }
      // 完整路径
      url+='?'+paramsStr;
      // 发送get
      promise = axios.get(url);
    }else if('POST'===type){
      promise=axios.post(url,params)
    }
    promise.then((response)=>{
      resolve(response.data)
    }).catch(error=>{
      reject(error)
    })
  })
}
